package com.wu.store.config;

import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;

import java.util.*;

@Configuration
public class ShiroConfig {
	@Bean
	public ShiroFilterFactoryBean webFilter() {
		ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

		Map<String, String> filterChainMap = new LinkedHashMap<>(16);
//		List<String> anonList = Arrays.asList(
//			"/",
//			"/login",
//			"/user/logout",
//			"/user/register",
//			"/user/isUsernameValid",
//			"/user/validateIsLogged",
//			"/index.html",
//			"/js/**",
//			"/css/**",
//			"/fonts/**",
//			"/img/**",
//			"/favicon.ico");
//		for (String url : anonList) {
//			filterChainMap.put(url, "anon");
//		}
//		filterChainMap.put("/**", "authc");
		filterChainMap.put("/**", "anon");
		shiroFilterFactoryBean.setLoginUrl("/login");
		shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainMap);
		shiroFilterFactoryBean.setSecurityManager(securityManager(customRealm(), oAuth2Realm()));
		return shiroFilterFactoryBean;
	}

	@Bean(name = "customRealm")
	public CustomRealm customRealm() {
		return new CustomRealm();
	}

	@Bean(name = "oAuth2Realm")
	public OAuth2Realm oAuth2Realm() {
		return new OAuth2Realm();
	}

	@Bean(name = "securityManager")
	public SecurityManager securityManager(@Qualifier("customRealm") CustomRealm customRealm, @Qualifier("oAuth2Realm") OAuth2Realm oAuth2Realm) {
		DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
		List<Realm> list = new ArrayList<>();
		list.add(customRealm);
		list.add(oAuth2Realm);
		securityManager.setRealms(list);
		return securityManager;
	}

	@Bean
	public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor(SecurityManager securityManager) {
		AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor = new AuthorizationAttributeSourceAdvisor();
		authorizationAttributeSourceAdvisor.setSecurityManager(securityManager);
		return authorizationAttributeSourceAdvisor;
	}

//	@Bean
//	public SimpleMappingExceptionResolver simpleMappingExceptionResolver() {
//		SimpleMappingExceptionResolver simpleMappingExceptionResolver = new SimpleMappingExceptionResolver();
//		Properties mappings = new Properties();
//		simpleMappingExceptionResolver.setExceptionMappings(mappings);
//		return simpleMappingExceptionResolver;
//	}
}
